import { effect$, closeForeground } from "@auto.pro/core";
import { from, fromEvent, race, timer } from "rxjs";
import { removeLimit, getIMEI } from "@/utils/index";
import { webview } from "@/auto-server/common/webview";
import settersFun from "@/auto-server/modules/setters";
import douyinFun from "@/auto-server/modules/douyin";
import floatButton from "@/auto-server/common/float-button";
import store from "@/auto-server/common/store";
import { customAlphabet } from 'nanoid';

settersFun();
douyinFun();

// effect$是作业线程，当core的权限全部到位后，effect$才开始运作
effect$.subscribe(() => {
  try {
    removeLimit();
    if ((auto.service || device.sdkInt < 24) && floaty.checkPermission()) {
      console.log("开启悬浮窗权限");
      floatButton.init();
    }
  } catch (error) {
    console.error(error);
  }
});
webview.on("getDeviceInfo").subscribe(([params, done]) => {
  let activeCode = store.get('activeCode') || '';
  let IMEI = store.get('IMEI') || '';
  let fingerprint = store.get('fingerprint') || '';
  let deviceID = store.get('deviceID') || '';
  if (!IMEI) {
    IMEI = getIMEI();
    store.put('IMEI', IMEI);
  }
  if (!fingerprint) {
    fingerprint = device.fingerprint || "";
    store.put('fingerprint', fingerprint);
  }
  if (!deviceID) {
    const nanoid = customAlphabet(IMEI, 10);
    store.put('deviceID', nanoid());
  }
  done({
    fingerprint,
    activeCode,
    IMEI,
    deviceID,
  });
});
// 更新store内激活码
webview.on("getDeviceInfo").subscribe(([params, done]) => {
  if (params.activeCode) {
    store.put('activeCode', params.activeCode);
  }
});
// 监听退出事件，关闭前台服务
events.on("exit", () => {
  closeForeground();
});
// 点击返回页面回退
fromEvent(ui.emitter, "back_pressed").subscribe((e) => {
  e.consumed = true;
  webview.runHtmlFunction("routeBack");
});
